package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.robot.admin.client.MemberClient;
import com.robot.admin.client.MerchantClient;
import com.robot.admin.pojo.vo.Index;
import com.robot.admin.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 首页
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private MemberClient memberClient;
    @Autowired
    private MerchantClient merchantClient;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 是否plus会员 0-游客/注册用户,1-付了一块钱->会员,2-付了198->plus会员
     */
    @Value("${sys.member.isPlus}")
    private String isPlusValue;


    /**
     * 会员数
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "members", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result members(@RequestBody Map searchMap) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        //判断是否plus会员 0-游客/注册用户,1-付了一块钱->会员,2-付了198->plus会员
        String isPlus = (String) searchMap.get("isPlus");
        if (isPlus == null || "".equals(isPlus)) {
            return new Result(StatusCode.ERROR, "isPlus参数必填");
        }
        if (!isValidIsPlus(isPlus)) {
            return new Result(StatusCode.ERROR, "isPlus参数错误");
        }

        int page = 1;
        int size = 10;
        //默认取最近7天
        JSONObject week = JSON.parseObject(memberClient.thirdFindMembersByIsPlusAndWeek(isPlus, page, size));
        //判断是否存在开始结束时间
        String startTime = (String) searchMap.get("startTime");
        String endTime = (String) searchMap.get("endTime");
        if (startTime != null && !"".equals(startTime) && endTime != null && !"".equals(endTime)) {
            if (!isValidDate(startTime)) {
                return new Result(StatusCode.ERROR, "请输入正确格式的开始时间");
            }
            if (!isValidDate(endTime)) {
                return new Result(StatusCode.ERROR, "请输入正确格式的结束时间");
            }
            //开始时间,结束时间都存在,则取开始结束之间的数据
            week = JSON.parseObject(memberClient.thirdFindMembersByIsPlusAndBetweenAnd(searchMap, page, size));
        } else if (startTime != null && !"".equals(startTime)) {
            if ((endTime == null || "".equals(endTime))) {
                return new Result(StatusCode.ERROR, "请输入结束时间");
            }
        } else if (endTime != null && !"".equals(endTime)) {
            if (startTime == null || "".equals(startTime)) {
                return new Result(StatusCode.ERROR, "请输入开始时间");
            }
        }

        Index members = new Index();
        //今日数据
        JSONObject today = JSON.parseObject(memberClient.thirdFindMembersByIsPlusAndToday(isPlus, page, size));
        //总的数据
        JSONObject total = JSON.parseObject(memberClient.thirdFindMembersByIsPlusAndTotal(isPlus, page, size));
        if (today == null) {
            logger.info("adminModule`s index call memberModule failed");
            members.setToday("0");
        } else {
            members.setToday(today.get("total").toString());
        }
        if (week == null) {
            logger.info("agentModule`s index call memberModule failed");
            members.setWeek("0");
        } else {
            members.setWeek(week.get("total").toString());
        }
        if (total == null) {
            logger.info("agentModule`s index call memberModule failed");
            members.setTotal("0");
        } else {
            members.setTotal(total.get("total").toString());
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("members", members);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 关注数
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "fans", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result fans(@RequestBody Map searchMap) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        //具体逻辑

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("fans", searchMap);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 商家数
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "stores", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Result stores(@RequestBody Map searchMap) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);


        int page = 1;
        int size = 10;
        //默认取最近7天
        JSONObject week = JSON.parseObject(merchantClient.thirdFindStoresByWeek(page, size));
        //判断是否存在开始结束时间
        String startTime = (String) searchMap.get("startTime");
        String endTime = (String) searchMap.get("endTime");
        if (startTime != null && !"".equals(startTime) && endTime != null && !"".equals(endTime)) {
            if (!isValidDate(startTime)) {
                return new Result(StatusCode.ERROR, "请输入正确格式的开始时间");
            }
            if (!isValidDate(endTime)) {
                return new Result(StatusCode.ERROR, "请输入正确格式的结束时间");
            }
            //开始时间,结束时间都存在,则取开始结束之间的数据
            week = JSON.parseObject(merchantClient.thirdFindStoresByBetweenAnd(searchMap, page, size));
        } else if (startTime != null && !"".equals(startTime)) {
            if ((endTime == null || "".equals(endTime))) {
                return new Result(StatusCode.ERROR, "请输入结束时间");
            }
        } else if (endTime != null && !"".equals(endTime)) {
            if (startTime == null || "".equals(startTime)) {
                return new Result(StatusCode.ERROR, "请输入开始时间");
            }
        }

        Index stores = new Index();
        //今日数据
        JSONObject today = JSON.parseObject(merchantClient.thirdFindStoresByToday(page, size));
        //总的数据
        JSONObject total = JSON.parseObject(merchantClient.thirdFindStoresByTotal(page, size));
        if (today == null) {
            logger.info("adminModule`s index call merchantModule failed");
            stores.setToday("0");
        } else {
            stores.setToday(today.get("total").toString());
        }
        if (week == null) {
            logger.info("agentModule`s index call merchantModule failed");
            stores.setWeek("0");
        } else {
            stores.setWeek(week.get("total").toString());
        }
        if (total == null) {
            logger.info("agentModule`s index call merchantModule failed");
            stores.setTotal("0");
        } else {
            stores.setTotal(total.get("total").toString());
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("stores", stores);
        return new Result(StatusCode.SUCCESS_QUERY, map);
    }

    /**
     * 判断时间格式是否正确
     *
     * @param str
     * @return
     */
    public static boolean isValidDate(String str) {
        return true;
    }

    /**
     * 判断isPlus是否正确,是否plus会员 0-游客/注册用户,1-付了一块钱->会员,2-付了198->plus会员
     *
     * @param isPlus 要判断的场景
     * @return true 存在 false 不存在
     */
    public boolean isValidIsPlus(String isPlus) {
        return isPlusValue.contains(isPlus);
    }
}
